package com.waa.gulimall.cart.service.Impl;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.TypeReference;
import com.waa.gulimall.cart.feign.ProductFeignService;
import com.waa.gulimall.cart.interceptor.CartInterceptor;
import com.waa.gulimall.cart.service.CartService;
import com.waa.gulimall.cart.to.UserInfoTo;
import com.waa.gulimall.cart.vo.Cart;
import com.waa.gulimall.cart.vo.CartItem;
import com.waa.gulimall.cart.vo.SkuInfoVo;
import com.waa.gulimall.common.utils.R;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.BoundHashOperations;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.stereotype.Service;

import java.math.BigDecimal;
import java.util.List;
import java.util.concurrent.CompletableFuture;
import java.util.concurrent.ExecutionException;
import java.util.concurrent.ThreadPoolExecutor;
import java.util.stream.Collectors;

@Service
@Slf4j
public class CartServiceImpl implements CartService {
    @Autowired
    private StringRedisTemplate stringRedisTemplate;
    @Autowired
    private ProductFeignService productFeignService;
    @Autowired
    private ThreadPoolExecutor threadPoolExecutor;
    private final String CART_PREFIX = "changggou:cart";


    @Override
    public CartItem addToCart(Long skuId, Integer num) throws ExecutionException, InterruptedException {
        final BoundHashOperations<String, Object, Object> cartOps = getCartOps();
        //远程调用当前要添加商品的信息
        final R info = productFeignService.info(skuId);
        SkuInfoVo skuInfoVo = (SkuInfoVo) info.getData("skuInfo", new TypeReference<SkuInfoVo>() {
        });
        //先从购物车中找这个商品
        final String res = (String) cartOps.get(skuId.toString());

        if (StringUtils.isEmpty(res)) {
            //新商品添加到购物车
            final CartItem cartItem = new CartItem();
            final CompletableFuture<Void> getSkuInfoTask = CompletableFuture.runAsync(() -> {
                cartItem.setCheck(true);
                cartItem.setCount(1);
                cartItem.setTitle(skuInfoVo.getSkuTitle());
                cartItem.setImage(skuInfoVo.getSkuDefaultImg());
                cartItem.setSkuId(skuId);
                cartItem.setPrice(skuInfoVo.getPrice());
            }, threadPoolExecutor);
            final CompletableFuture<Void> getSkuSaleAttrValues = CompletableFuture.runAsync(() -> {
                final List<String> skuSaleAttrValue = productFeignService.getSkuSaleAttrValue(skuId);
                cartItem.setSkuAttr(skuSaleAttrValue);//远程调用
            }, threadPoolExecutor);
            //等待所有的异步任务都完成后
            CompletableFuture.allOf(getSkuInfoTask, getSkuSaleAttrValues).get();
            final String js = JSON.toJSONString(cartItem);
            cartOps.put(skuId.toString(), js);
            return cartItem;
        } else {
            // 购物车有此商品，修改数量
            final CartItem cartItem =JSON.parseObject(res, CartItem.class);
            cartItem.setCount(cartItem.getCount() + num);
            cartOps.put(skuId.toString(),JSON.toJSONString(cartItem));
            return cartItem;
        }


    }

    //获取购物车的内容
    @Override
    public Cart getCart() throws ExecutionException, InterruptedException {
        final Cart cart = new Cart();
        final UserInfoTo userInfoTo = CartInterceptor.threadLocal.get();
       //判断是否登录
        if (userInfoTo.getUserId()!=null){
            //已登录·
            String cartKey = CART_PREFIX + userInfoTo.getUserId();
           //判断临时购物车中有没有数据[合并购物车]
           String tempCartKey =  CART_PREFIX + userInfoTo.getUserKey();
            final List<CartItem> cartItems = getCartItems(tempCartKey);
            if (cartItems != null && cartItems.size() > 0){//如果有数据
             //临时购物车有数据
                for (CartItem cartItem : cartItems) {
                    addToCart(cartItem.getSkuId(),cartItem.getCount());
                }
                //清空购物车
                clearCart(tempCartKey);
            }
            //获取登录后购物车的数据，包括临时购物车的数据，和登陆后的数据
            final List<CartItem> itemList = getCartItems(cartKey);
            cart.setItems(itemList);
        }else {
            //未登录
            String cartKey = CART_PREFIX + userInfoTo.getUserKey();
            //获取临时购物车的购物项
            List<CartItem> cartItems = getCartItems(cartKey);
            cart.setItems(cartItems);
        }
        return cart;
    }
    //清空购物车
    @Override
    public void  clearCart(String cartKey){
            stringRedisTemplate.delete(cartKey);
    }

    //更改检查项状态是否被选中
    @Override
    public void checkItem(Long skuId, Integer checked) {
        final BoundHashOperations<String, Object, Object> cartOps = getCartOps();
        final CartItem cartItem = getCartItem(skuId);
        cartItem.setCheck(checked == 1 ? true:false);
        final String js = JSON.toJSONString(cartItem);
        cartOps.put(skuId.toString(),js);//更新redis
    }

    @Override
    public void updateItem(Long skuId, Integer count) {
        // 1、用户在页面对某个购物项增加或减少购物项的数量，那么redis中应该也要进行更新
        CartItem cartItem = getCartItem(skuId);
        cartItem.setCount(count);
        BoundHashOperations<String, Object, Object> cartOps = getCartOps();
        cartOps.put(skuId.toString(),JSON.toJSONString(cartItem)); // 更新redis中数据
    }

    private CartItem getCartItem(Long skuId) {
        final BoundHashOperations<String, Object, Object> cartOps = getCartOps();
        //从redis中直接查出购物项设置是否被选中
        final String cart = (String) cartOps.get(skuId.toString());
        final CartItem cartItem = JSON.parseObject(cart, CartItem.class);
        return cartItem;
    }

    @Override
    public void deleteItem(Long skuId) {
        // 获取到当前购物车，然后根据id删除购物车里面的购物项
        BoundHashOperations<String, Object, Object> cartOps = getCartOps();
        cartOps.delete(skuId.toString());
    }

    /**
     *
     * 回去购物车登录后的购物项
     * @return
     */
    @Override
    public List<CartItem> getUserCartItems() {
        final UserInfoTo userInfoTo = CartInterceptor.threadLocal.get();
        //判断是否登录
        if (userInfoTo.getUserId() == null){
            return null;
        }else {
         String cartKey = CART_PREFIX + userInfoTo.getUserId();
            final List<CartItem> cartItems = getCartItems(cartKey);
            //获取所有被选中的购物项
            final List<CartItem> collect = cartItems.stream().filter(item -> item.getCheck()).map(
                    item->{
                        //TODO 更新为最新价格
                        final R price = productFeignService.getPrice(item.getSkuId());
                        item.setPrice(new BigDecimal((String) price.get("data")));
                        return item;
                    }
            ).collect(Collectors.toList());
        }
        return null;
    }

    //获取临时购物车的购物项
    private List<CartItem> getCartItems(String cartKey) {
        final BoundHashOperations<String, Object, Object> hashOps = stringRedisTemplate.boundHashOps(cartKey);
        final List<Object> values = hashOps.values();
        if (values!=null&&values.size()>0){
            final List<CartItem> collect = values.stream().map(obj -> {
                String js = (String) obj;
                final CartItem cartItem = JSON.parseObject(js, CartItem.class);
                return cartItem;
            }).collect(Collectors.toList());
            return collect;
        }
        return null;
    }

    /**
     * 获取我们要操作的购物车
     */
    public BoundHashOperations<String, Object, Object> getCartOps() {
        final UserInfoTo userInfoTo = CartInterceptor.threadLocal.get();
        //
        String cartKey = "";
        if (null!=userInfoTo) {
            if (userInfoTo.getUserId() != null) {
                //已登录
                cartKey = CART_PREFIX + userInfoTo.getUserId();
            } else {
                //未登录
                cartKey = CART_PREFIX + userInfoTo.getUserKey();

            }
        }
        final BoundHashOperations<String, Object, Object> hashOps = stringRedisTemplate.boundHashOps(cartKey);
        return hashOps;
    }

}

